package server.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import server.config.ServerConfig;
import server.container.Feuerwehr;
import server.db.FeuerwehrCache;
import server.db.SQL;

public class FeuerwehrenImAlarmierungTableUpdaten {

	private static Logger logger = Logger
			.getLogger(CacheTableNeuErstellen.class);

	public static void main(String[] args) {

		PropertyConfigurator.configure("log4J.cfg");
		try {
			new ServerConfig("serverConfigLocal.cfg");
			SQL.getInstance();

			try {

				SQL.fillFeuerwehrCache();

				Connection con = SQL.getInstance().getConPool()
						.getConnectionFromPool();
				PreparedStatement stmt;
				stmt = con
						.prepareStatement("SELECT id, alarmkennung, feuerwehrid FROM `alarmierung`");

				ResultSet rs = stmt.executeQuery();

				while (rs.next()) {

//					 if (rs.getInt("id") < 36354) {
//					 continue;
//					 }

					Feuerwehr fw = FeuerwehrCache.getFeuerwehrBySchleife(rs
							.getString("alarmkennung"));

					
					if (fw != null) {

						if (fw.getId() != rs.getInt("feuerwehrid")) {
							System.out.println(rs.getInt("id"));
							PreparedStatement stmt3 = con
									.prepareStatement("UPDATE `alarmierung` SET feuerwehrid = '"
											+ fw.getId()
											+ "' WHERE id = '"
											+ rs.getInt("id") + "'");
							stmt3.executeUpdate();
							stmt3.close();
						}

					} else {
						if (rs.getInt("feuerwehrid") != -1) {
							System.out.println(rs.getInt("id"));
							PreparedStatement stmt3 = con
									.prepareStatement("UPDATE `alarmierung` SET feuerwehrid = '-1' WHERE id = '"
											+ rs.getInt("id") + "'");
							stmt3.executeUpdate();
							stmt3.close();
						}
					}

				}
			} catch (SQLException e) {
				logger.error("SQLException", e);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}